﻿using System;
using System.Threading;

namespace Jiubang.Communication.Server.Buffers {
    /// <summary>
    /// 可共享缓冲区计数器
    /// </summary>
    internal sealed class ShareBufferCounter {
        private int _counter;

        /// <summary>
        /// 当前缓冲区增加共享计算
        /// </summary>
        /// <param name="delta"></param>
        internal void AddShareCount(int delta) {
            if (delta <= 0)
                throw new ArgumentOutOfRangeException("delta");

            Interlocked.Add(ref _counter, delta);
        }

        /// <summary>
        /// 使共享计数器自减1。
        /// </summary>
        /// <returns></returns>
        internal int Release() {
            return Interlocked.Decrement(ref _counter);
        }

        internal void Set(int initialValue) {
            if (initialValue < 0)
                throw new ArgumentOutOfRangeException();
            _counter = initialValue;
        }
    }
}